<template>
	<div class="wrapper">
	  <header>
		<p>我的订单</p>
		<i class="fa fa-refresh refresh-btn" @click="refreshOrders" :class="{ 'refreshing': isRefreshing }"></i>
	  </header>
	  
	  <!-- 可滚动的主内容区域 -->
	  <div class="main-content">
		<div v-if="isLoading" class="loading">
		  <p>正在加载订单信息...</p>
		</div>
		
		<div v-else>
		  <h3>未支付订单信息：</h3>
		  <div v-if="orderUnpaidArr.length === 0" class="empty-state">
			<p>暂无未支付订单</p>
		  </div>
		  <ul class="order" v-else>
			<li
			  v-for="item in orderUnpaidArr"
			  :key="item.orderId"
			>
			<div class="order-info">
			  <p>
				{{ item.business.businessName }}
				<i class="fa fa-caret-down" @click="detailetShow(item)"></i>
			  </p>
			  <div class="order-info-right">
				<p>&#165;{{ item.orderTotal }}</p>
				<div class="order-info-right-icon" @click="goToPayment(item.orderId)">去支付</div>
			  </div>
			</div>
			<ul class="order-detailet" v-show="item.isShowDetailet">
			  <!-- 订单时间信息 -->
			  <li class="order-time-info">
				<div class="time-section">
				  <p class="time-title">下单时间：</p>
				  <p class="time-detail">{{ item.orderDate }}</p>
				</div>
			  </li>
			  
			  <!-- 配送地址信息（使用快照数据） -->
			  <li class="address-info">
				<div class="address-section">
				  <p class="address-title">配送地址：</p>
				  <p class="address-detail">{{ item.address || '地址信息加载中...' }}</p>
				  <p class="contact-detail" v-if="item.contactName">
					{{ item.contactName }}{{ item.contactSex == 1 ? '先生' : '女士' }} {{ item.contactTel || '' }}
				  </p>
				  <p class="contact-detail" v-else-if="item.contactTel">
					联系电话：{{ item.contactTel }}
				  </p>
				  <p class="debug-info" v-if="!item.contactName && !item.address" style="font-size: 2.5vw; color: #f90;">
					⚠️ 快照数据未加载，请重启后端服务
				  </p>
				</div>
			  </li>
			  
			  <!-- 商品明细（使用快照数据） -->
			  <li v-for="odItem in item.list" :key="odItem.odId" class="food-item">
				<div class="food-info">
				  <p class="food-name">{{ getFoodDisplayName(odItem) }}</p>
				  <p class="food-desc" v-if="getFoodDisplayExplain(odItem)">{{ getFoodDisplayExplain(odItem) }}</p>
				  <p class="food-quantity">数量：{{ odItem.quantity }}</p>
				</div>
				<p class="food-price">&#165;{{ (getFoodDisplayPrice(odItem) * odItem.quantity).toFixed(2) }}</p>
			  </li>
			  
			  <!-- 配送费 -->
			  <li class="delivery-fee">
				<p>配送费</p>
				<p>&#165;{{ item.business.deliveryPrice }}</p>
			  </li>
			</ul>
			</li>
		  </ul>
	
		  <h3>已支付订单信息：</h3>
		  <div v-if="orderPaidArr.length === 0" class="empty-state">
			<p>暂无已支付订单</p>
		  </div>
		  <ul class="order" v-else>
			<li
			  v-for="item in orderPaidArr"
			  :key="item.orderId"
			>
			<div class="order-info">
			  <p>
				{{ item.business.businessName }}
				<i class="fa fa-caret-down" @click="detailetShow(item)"></i>
			  </p>
			  <div class="order-info-right">
				<p>&#165;{{ item.orderTotal }}</p>
				<div class="order-status">{{ getOrderStatusText(item.orderState) }}</div>
			  </div>
			</div>
			<ul class="order-detailet" v-show="item.isShowDetailet">
			  <!-- 订单时间信息 -->
			  <li class="order-time-info">
				<div class="time-section">
				  <p class="time-title">下单时间：</p>
				  <p class="time-detail">{{ item.orderDate }}</p>
				</div>
			  </li>
			  
			  <!-- 配送地址信息（使用快照数据） -->
			  <li class="address-info">
				<div class="address-section">
				  <p class="address-title">配送地址：</p>
				  <p class="address-detail">{{ item.address || '地址信息加载中...' }}</p>
				  <p class="contact-detail" v-if="item.contactName">
					{{ item.contactName }}{{ item.contactSex == 1 ? '先生' : '女士' }} {{ item.contactTel || '' }}
				  </p>
				  <p class="contact-detail" v-else-if="item.contactTel">
					联系电话：{{ item.contactTel }}
				  </p>
				  <p class="debug-info" v-if="!item.contactName && !item.address" style="font-size: 2.5vw; color: #f90;">
					⚠️ 快照数据未加载，请重启后端服务
				  </p>
				</div>
			  </li>
			  
			  <!-- 商品明细（使用快照数据） -->
			  <li v-for="odItem in item.list" :key="odItem.odId" class="food-item">
				<div class="food-info">
				  <p class="food-name">{{ getFoodDisplayName(odItem) }}</p>
				  <p class="food-desc" v-if="getFoodDisplayExplain(odItem)">{{ getFoodDisplayExplain(odItem) }}</p>
				  <p class="food-quantity">数量：{{ odItem.quantity }}</p>
				</div>
				<p class="food-price">&#165;{{ (getFoodDisplayPrice(odItem) * odItem.quantity).toFixed(2) }}</p>
			  </li>
			  
			  <!-- 配送费 -->
			  <li class="delivery-fee">
				<p>配送费</p>
				<p>&#165;{{ item.business.deliveryPrice }}</p>
			  </li>
			</ul>
			</li>
		  </ul>
		</div>
	  </div>
  
	  <!-- 底部菜单部分 -->
	  <Footer></Footer>
	</div>
  </template>
  
  <script setup>
  import Footer from "../components/Footer.vue";
  import qs from "qs";
  import { useRouter, useRoute } from "vue-router";
  import { ref, inject } from "vue";
  import { getSessionStorage } from "../common.js";
  
  const axios = inject("axios");
  const router = useRouter();
  const route = useRoute();
  
  const user = getSessionStorage("user");
  const orderPaidArr = ref([]);
  const orderUnpaidArr = ref([]);
  const isLoading = ref(true);
  const isRefreshing = ref(false);
  
  const init = () => {
	console.log('OrderList页面初始化，用户ID:', user.userId);
	axios
	  .post(
		"/api/OrdersController/listOrdersByUserId", // 修复：添加/api/前缀
		qs.stringify({
		  userId: user.userId,
		})
	  )
	  .then((response) => {
		console.log('获取订单列表API响应:', response);
		let result = response; // 修复：直接使用response
		for (let orders of result) {
		  orders.isShowDetailet = false;
		  // 修复订单状态分类逻辑
		  // 0:已取消, 1:已下单(未支付), 2:已支付, 3:配送中, 4:已送达
		  console.log(`订单${orders.orderId}状态: ${orders.orderState}`);
		  if(orders.orderState == 1) {
			  orderUnpaidArr.value.push(orders); // 已下单但未支付
		  }
		  if(orders.orderState >= 2) {
			  orderPaidArr.value.push(orders); // 已支付及以后状态
		  }
		}
		console.log('未支付订单数量:', orderUnpaidArr.value.length);
		console.log('已支付订单数量:', orderPaidArr.value.length);
	  })
	  .catch((error) => {
		console.error('获取订单列表失败:', error);
		alert('获取订单列表失败，请稍后重试！');
	  })
	  .finally(() => {
		isLoading.value = false;
	  });
  };
  init();
  
  const detailetShow = (orders) => {
	orders.isShowDetailet = !orders.isShowDetailet;
	
	// 添加调试信息，帮助诊断问题
	if (orders.isShowDetailet) {
	  console.log('订单详情数据:', {
		orderId: orders.orderId,
		contactName: orders.contactName,
		contactTel: orders.contactTel,
		address: orders.address,
		orderState: orders.orderState,
		fullOrderData: orders
	  });
	}
  };

  const goToPayment = (orderId) => {
	console.log('跳转到支付页面，订单ID:', orderId);
	router.push({ 
	  path: '/payment', 
	  query: { orderId: orderId } 
	});
  };

  const getOrderStatusText = (orderState) => {
	const statusMap = {
	  0: '已取消',
	  1: '待支付',
	  2: '已支付',
	  3: '配送中',
	  4: '已送达'
	};
	return statusMap[orderState] || '未知状态';
  };

  // 获取商品显示名称（优先使用快照数据）
  const getFoodDisplayName = (odItem) => {
	return odItem.foodName || (odItem.food && odItem.food.foodName) || '商品名称缺失';
  };

  // 获取商品显示价格（优先使用快照数据）
  const getFoodDisplayPrice = (odItem) => {
	return odItem.foodPrice || (odItem.food && odItem.food.foodPrice) || 0;
  };

  // 获取商品显示介绍（优先使用快照数据）
  const getFoodDisplayExplain = (odItem) => {
	return odItem.foodExplain || (odItem.food && odItem.food.foodExplain) || '';
  };

  const refreshOrders = () => {
	if (isRefreshing.value) return; // 防止重复刷新
	
	isRefreshing.value = true;
	console.log('手动刷新订单列表');
	
	// 滚动到顶部
	const mainContent = document.querySelector('.main-content');
	if (mainContent) {
	  mainContent.scrollTo({ top: 0, behavior: 'smooth' });
	}
	
	// 清空当前数据
	orderPaidArr.value = [];
	orderUnpaidArr.value = [];
	
	// 重新初始化
	init();
	
	// 刷新动画持续1秒
	setTimeout(() => {
	  isRefreshing.value = false;
	}, 1000);
  };
  </script>
  
  <style scoped>
  /****************** 总容器 ******************/
  .wrapper {
	width: 100%;
	height: 100vh;
	display: flex;
	flex-direction: column;
	overflow: hidden;
  }
  
  /****************** 主内容区域 ******************/
  .main-content {
	flex: 1;
	overflow-y: auto;
	overflow-x: hidden;
	padding-bottom: 20vw; /* 为底部Footer预留空间 */
	-webkit-overflow-scrolling: touch; /* iOS 平滑滚动 */
	scroll-behavior: smooth; /* 平滑滚动 */
  }

  /* 滚动条样式优化 */
  .main-content::-webkit-scrollbar {
	width: 2px;
  }

  .main-content::-webkit-scrollbar-track {
	background: #f1f1f1;
  }

  .main-content::-webkit-scrollbar-thumb {
	background: #c1c1c1;
	border-radius: 1px;
  }

  .main-content::-webkit-scrollbar-thumb:hover {
	background: #a8a8a8;
  }

  /****************** 加载状态 ******************/
  .loading {
	width: 100%;
	margin-top: 15vw; /* 为header预留空间 */
	padding: 10vw;
	text-align: center;
	color: #666;
	font-size: 4vw;
  }
  
  /****************** 空状态 ******************/
  .empty-state {
	width: 100%;
	padding: 8vw 4vw;
	text-align: center;
	color: #999;
	font-size: 3.5vw;
	background-color: #f9f9f9;
	margin: 2vw 0;
  }
  
  /****************** header部分 ******************/
  .wrapper header {
	width: 100%;
	height: 12vw;
	background-color: #0097ff;
	color: #fff;
	font-size: 4.8vw;
  
	position: fixed;
	left: 0;
	top: 0;
	z-index: 1000;
  
	display: flex;
	justify-content: center;
	align-items: center;
	position: relative;
  }
  
  .wrapper header .refresh-btn {
	position: absolute;
	right: 4vw;
	font-size: 4vw;
	cursor: pointer;
	transition: all 0.3s ease;
	padding: 2vw;
  }
  
  .wrapper header .refresh-btn:hover {
	opacity: 0.8;
  }
  
  .wrapper header .refresh-btn.refreshing {
	animation: spin 1s linear infinite;
  }
  
  @keyframes spin {
	from { transform: rotate(0deg); }
	to { transform: rotate(360deg); }
  }
  
  /****************** 历史订单列表部分 ******************/
  .wrapper h3 {
	margin-top: 0;
	box-sizing: border-box;
	padding: 4vw;
	font-size: 4vw;
	font-weight: 300;
	color: #999;
	background-color: #fafafa;
	border-bottom: 1px solid #eee;
	position: sticky;
	top: 0;
	z-index: 100;
  }

  .wrapper h3:first-of-type {
	margin-top: 12vw; /* 第一个标题需要为header预留空间 */
  }
  
  .wrapper .order {
	width: 100%;
  }
  
  .wrapper .order li {
	width: 100%;
  }
  
  .wrapper .order li .order-info {
	box-sizing: border-box;
	padding: 2vw 4vw;
	font-size: 4vw;
	color: #666;
  
	display: flex;
	justify-content: space-between;
	align-items: center;
  }

  .wrapper .order li .order-info p {
	display: flex;
	align-items: center;
	gap: 2vw;
  }
  
  .wrapper .order li .order-info .order-info-right {
	display: flex;
	flex-direction: column;
	align-items: flex-end;
	gap: 1vw;
  }
  
  .wrapper .order li .order-info .order-info-right .order-info-right-icon {
	background-color: #f90;
	color: #fff;
	border-radius: 3px;
	padding: 1vw 2vw;
	font-size: 3vw;
	user-select: none;
	cursor: pointer;
	transition: all 0.3s ease;
  }
  
  .wrapper .order li .order-info .order-info-right .order-info-right-icon:hover {
	background-color: #e6800e;
	transform: scale(0.95);
  }
  
  .wrapper .order li .order-info .order-info-right .order-status {
	background-color: #38ca73;
	color: #fff;
	border-radius: 3px;
	padding: 1vw 2vw;
	font-size: 3vw;
	user-select: none;
  }
  
  .wrapper .order li .order-detailet {
	width: 100%;
	background-color: #f9f9f9;
	border-top: 1px solid #eee;
  }

  /****************** 订单时间信息样式 ******************/
  .wrapper .order li .order-detailet .order-time-info {
	width: 100%;
	background-color: #f0f8ff;
	border-bottom: 1px solid #d0d0d0;
  }

  .wrapper .order li .order-detailet .order-time-info .time-section {
	padding: 2vw 4vw;
  }

  .wrapper .order li .order-detailet .order-time-info .time-title {
	font-size: 3.2vw;
	color: #666;
	font-weight: bold;
	margin-bottom: 0.5vw;
  }

  .wrapper .order li .order-detailet .order-time-info .time-detail {
	font-size: 3.5vw;
	color: #333;
	font-weight: 500;
  }

  /****************** 配送地址信息样式 ******************/
  .wrapper .order li .order-detailet .address-info {
	width: 100%;
	background-color: #e8f4fd;
	border-bottom: 1px solid #d0d0d0;
  }

  .wrapper .order li .order-detailet .address-info .address-section {
	padding: 2vw 4vw;
  }

  .wrapper .order li .order-detailet .address-info .address-title {
	font-size: 3.2vw;
	color: #0097ff;
	font-weight: bold;
	margin-bottom: 1vw;
  }

  .wrapper .order li .order-detailet .address-info .address-detail {
	font-size: 3.5vw;
	color: #333;
	margin-bottom: 0.5vw;
  }

  .wrapper .order li .order-detailet .address-info .contact-detail {
	font-size: 3vw;
	color: #666;
  }

  /****************** 商品项目样式 ******************/
  .wrapper .order li .order-detailet .food-item {
	width: 100%;
	box-sizing: border-box;
	padding: 2vw 4vw;
	color: #666;
	border-bottom: 1px solid #eee;
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
  }

  .wrapper .order li .order-detailet .food-item .food-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 0.5vw;
  }

  .wrapper .order li .order-detailet .food-item .food-name {
	font-size: 3.5vw;
	color: #333;
	font-weight: 500;
  }

  .wrapper .order li .order-detailet .food-item .food-desc {
	font-size: 3vw;
	color: #999;
	line-height: 1.2;
  }

  .wrapper .order li .order-detailet .food-item .food-quantity {
	font-size: 3vw;
	color: #666;
  }

  .wrapper .order li .order-detailet .food-item .food-price {
	font-size: 3.5vw;
	color: #f90;
	font-weight: bold;
	text-align: right;
	min-width: 20vw;
  }

  /****************** 配送费样式 ******************/
  .wrapper .order li .order-detailet .delivery-fee {
	width: 100%;
	box-sizing: border-box;
	padding: 2vw 4vw;
	color: #666;
	font-size: 3.5vw;
	background-color: #f0f0f0;
	display: flex;
	justify-content: space-between;
	align-items: center;
	font-weight: bold;
  }
  </style>